﻿using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using tju.cme.BookStore2024.webapi.Models.EF;
using tju.cme.BookStore2024.webapi.Models.Tools;
using tju.cme.BookStore2024.webapi.Models.ViewModels.Admin;

namespace tju.cme.BookStore2024.webapi.Services
{
    /// <summary>
    /// 表T022administrator相关的服务
    /// </summary>
    /// <param name="context"></param>
    /// <param name="configuration"></param>
    public class AdminServices(BookStore2024Context context , IConfiguration configuration)
    {
        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<JwtSecurityToken> AdminLoginAsync(AdminLoginModel model)
        {
            //取出与填入用户名相同的用户信息放进item
            var item = await context.T022administrators.FirstOrDefaultAsync(m => m.UserName == model.UserName);
            if (item == null)
                throw new Exception("错误的帐号密码");
            var pwd = Util.MD5(model.Password);
            if (model.UserName == item.UserName && pwd == item.Password.ToUpper())
            {
                var claims = new List<Claim>
                {
                    //一个对用户ID和姓名的集合
                    new Claim(ClaimTypes.Sid, item.Id.ToString()),
                    new Claim(ClaimTypes.Name, item.UserName),
                    new Claim(ClaimTypes.Role, "Admin")
                };


                //sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit.
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSecurityKey"]!));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                    claims: claims,//凭据
                    expires: DateTime.Now.AddMinutes(30), //过期时间 30min后失效
                    signingCredentials: creds);  //加密后的密码
                return token;
            }
            throw new Exception("错误的帐号密码");
        }



        ///// <summary>
        ///// 上传特定章节
        ///// </summary>
        ///// <param name="id"></param>
        ///// <param name="isUpload"></param>
        ///// <returns></returns>
        //public async Task UploadChapterAsync(Guid chapterId)
        //{
        //    // 查询具有指定ID的章节记录
        //    var chapter = await context.T032chapters.FirstOrDefaultAsync(m => m.Id == chapterId);
        //    int totalUpload = await context.T032chapters.CountAsync(m => m.IsUpload == true);
         
        //    if (chapter != null && chapter.IsUpload==false ) {
        //        if (chapter.ChapterNumber - totalUpload == 1)
        //        {
        //            chapter.IsUpload = true;
        //            // 保存更改到数据库
        //            await context.SaveChangesAsync();
        //        }

        //    }
         
            
        //}

        /// <summary>
        /// 创建管理员账户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task CreateAdminAsync(AdminCreateModel model)
        {
            var newAdmin = new T022administrator()
            {
                Id = Guid.NewGuid(),
                UserName = model.UserName,
                Password = Util.MD5(model.Password),
            };
            
            await context.T022administrators.AddAsync(newAdmin);
            await context.SaveChangesAsync();
        }
    }
}
